﻿using ConcreteService;
using Models;
using System;
using System.Linq;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace SponsorshipWeb.Controllers
{
    public class UtilController : ApiController
    {
        //
        // GET: /Util/
        UtilService utilService = ServiceFactory.CreateInstance<UtilService>();

        [HttpGet]
        public IHttpActionResult ListBaseData(BaseDataFun fun)
        {
            var lst = AppConfig.ListRuleByFun(fun);

            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        [HttpPost]
        public IHttpActionResult LogError([FromBody]ExceptionMessage value)
        {
            LogUtil.Create("System", EventType.SysError, "SysError", value.ToString());

            return Ok();
        }

        [HttpPost]
        public IHttpActionResult ListEventLog([FromBody]JObject value)
        {
            var dic = ListSearchCondition(value);

            var lst = utilService.ListEventLog(dic, GetIntValue(value, "Start"), GetIntValue(value, "Limit"));

            return Ok(new JsonResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseJson = lst
            });
        }

        private IDictionary<SearchKey, string> ListSearchCondition(JObject value)
        {
            IDictionary<SearchKey, string> dic = new Dictionary<SearchKey, string>();

            dic.Add(SearchKey.StartDate, GetValue(value, SearchKey.StartDate));
            dic.Add(SearchKey.EndDate, GetValue(value, SearchKey.EndDate));
            dic.Add(SearchKey.Operator, GetValue(value, SearchKey.Operator));
            dic.Add(SearchKey.EventType, GetValue(value, SearchKey.EventType));
            dic.Add(SearchKey.EventObject, GetValue(value, SearchKey.EventObject));
            dic.Add(SearchKey.EventID, GetValue(value, SearchKey.EventID));

            return dic;
        }

        private string GetValue(JObject value, Enum name)
        {
            if (value == null)
                return string.Empty;

            return value[name.ToString()] == null ? string.Empty : value[name.ToString()].ToString();
        }

        private int GetIntValue(JObject value, string name)
        {
            if (value == null)
                return 0;

            return value[name] == null ? 0 : value[name].ToString().ToInt();
        }

    }
}